package com.shiyipicture.shiyipicturebackend.manager.upload;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpResponse;
import cn.hutool.http.HttpStatus;
import cn.hutool.http.HttpUtil;
import cn.hutool.http.Method;
import com.shiyipicture.shiyipicturebackend.exception.BusinessException;
import com.shiyipicture.shiyipicturebackend.exception.ErrorCode;
import com.shiyipicture.shiyipicturebackend.exception.ThrowUtils;
import org.springframework.stereotype.Service;

import java.io.File;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Arrays;
import java.util.List;

@Service
public class UrlPictureUpload extends FileManagerTemplate{
  @Override
  protected void processFile(Object inputSource, File file) {
    String fileUrl = (String)inputSource;
    HttpUtil.downloadFile(fileUrl,file);
  }

  @Override
  protected String getOriginalFileName(Object inputSource) {
    String fileUrl = (String)inputSource;
    return FileUtil.mainName(fileUrl);
  }

  @Override
  protected void validPicture(Object inputSource) {
    String fileUrl = (String)inputSource;
    ThrowUtils.throwIf(StrUtil.isBlank(fileUrl), ErrorCode.PARAMS_ERROR,"路径不能为空");
    try {
      // 验证URL格式
      new URL(fileUrl);
      // 2. 校验 URL 协议
      if (!(fileUrl.startsWith("https://") ||fileUrl.startsWith("http://"))) {
        throw new BusinessException(ErrorCode.PARAMS_ERROR,"仅支持https 或 http协议的文件地址");
      }
      HttpResponse response = null;
      // 3. 发送 HEAD 请求以验证文件是否存在
      response = HttpUtil.createRequest(Method.HEAD, fileUrl).execute();
      if (response.getStatus() != HttpStatus.HTTP_OK) {
        return;
      }
      //校验文件类型
      String contentType = response.header("Content-Type");
      if (StrUtil.isNotBlank(contentType)) {
        final List<String> ALLOW_FORMAT_LIST = Arrays.asList("image/jpg","image/jpeg","image/png","image/webg");
        ThrowUtils.throwIf(!ALLOW_FORMAT_LIST.contains(contentType.toLowerCase()),ErrorCode.PARAMS_ERROR,"图片格式不正确");
      }
      //校验文件大小
      String contentLengthStr = response.header("Content-Length");
      if (StrUtil.isNotBlank(contentLengthStr)) {
        long size = Long.parseLong(contentLengthStr);
        final long ONE_M = 1024 * 1024L;
        ThrowUtils.throwIf(size > 2 * size,ErrorCode.PARAMS_ERROR,"图片大小不能超过2MB");
      }
    } catch (MalformedURLException e) {
      throw new BusinessException(ErrorCode.PARAMS_ERROR,"路径格式不正确");
    }

  }
}
